# -*- coding:utf-8 -*-
from bson import ObjectId

__author__ = 'tsdykj'

import sys

sys.path.append('..')
from mongoer import dbobjects

from whoosh_helper import pdf_whoosh
import json
from flask import Flask, request, Response, render_template, redirect, url_for,flash
from flask_bootstrap import Bootstrap
from flask_flatpages import FlatPages
from flask_login import LoginManager, login_user, current_user,login_required,logout_user, UserMixin
from paginator import *

DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'

login_manager = LoginManager()

def create_app():
    app = Flask(__name__)
    Bootstrap(app)
    app.config.from_object('fileconfig')
    return app

app = create_app()
pages = FlatPages(app)
login_manager.setup_app(app)

num_posts_per_page = dbobjects.settings.find_one({'name': 'post_per_page'})['value']

class user(UserMixin):

    def __init__(self, dbuser):
        self.dbuser = dbuser

    def get_id(self):
        return str(self.dbuser['_id'])

@login_manager.user_loader
def load_user(userid):
    pdfuser = dbobjects.pdfusers.find_one({'_id': ObjectId(userid)})
    return user(pdfuser)

@app.route("/login/", methods=['POST', 'GET'])
def login():
    error = []
    if request.method == 'POST':
        username = request.form['username']
        pwd = request.form['password']

        pdfuser = dbobjects.pdfusers.find_one({'username': username})

        if pdfuser:
            if pdfuser['password'] == pwd:
                login_user(user(pdfuser))
                return redirect(url_for('index'))
            else:
                error.append(u'请输入正确的密码')
        else:
            error.append(u'用户不存在')

    notice_left = ''
    notice_right = ''

    notice = dbobjects.notices.find_one({})

    if notice:
        notice_left = notice['notice_left']
        notice_right = notice['notice_right']

    return render_template('login.html', error=error, notice_left=notice_left, notice_right=notice_right)

@app.route('/admin')
@login_required
def admin():
    return render_template('index.html', name='admin')

@app.route('/index')
@login_required
def index():
    if current_user:
        return render_template('index.html', name=current_user.dbuser['username'])
    else:
        return redirect(url_for('login'))

@app.route('/<path:path>/')
def page(path):
    page = pages.get_or_404(path)
    return render_template('page.html', page=page)

@app.route('/files/<id>', methods=['GET'])
def api_get_file(id):
    return 'you will get file id is: ' + id


@app.route('/search/<querytype>/<querystr>', methods=['GET'])
def api_search(querytype, querystr):
    if 'page' in request.args:
        page = int(request.args['page'])
    else:
        page = 0

    qtype = 'and'
    if querytype in ['or', 'and']:
        qtype = querytype

    hits, ids = searcher.search(querystr, qtype)

    paginator = Paginator(ids, num_posts_per_page)

    items = paginator[page]

    js = {
        'hits': hits,
        'pages': hits / num_posts_per_page,
        'ids': [i for i in items]
    }

    from bson import json_util

    js = json.dumps(js, default=json_util.default)

    resp = Response(js, status=200, mimetype='application/json')
    return resp


@app.route('/richsearch/<querytype>/<querystr>', methods=['GET'])
def api_rich_search(querytype, querystr):
    qtype = 'and'
    if querytype in ['or', 'and']:
        qtype = querytype

    hits, ids = searcher.search(querystr, qtype)

    from bson.objectid import ObjectId

    lines = []
    for id in ids:
        lines.append(dbobjects.texts.find_one({'_id': ObjectId(id)}))

    js = {
        'hits': hits,
        'lines': lines
    }

    from bson import json_util

    js = json.dumps(js, default=json_util.default)
    resp = Response(js, status=200, mimetype='application/json')
    return resp


@app.route('/files', methods=['GET'])
def api_all_files():
    from bson import json_util

    js = json.dumps([x for x in dbobjects.texts.find()], default=json_util.default)

    resp = Response(js, status=200, mimetype='application/json')
    return resp


if __name__ == '__main__':
    # define searcher for whoosh
    searcher = pdf_whoosh.textsearch()
    searcher.build()
    app.run()